package com.mjgy.service.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mjgy.entity.DeviceCodeEntity;
import com.mjgy.entity.MUserEntity;
import com.mjgy.entity.TokenEntity;
import com.mjgy.repository.DeviceCodeRepository;
import com.mjgy.repository.TokenRepository;
import com.mjgy.service.TokenService;
import com.mjgy.utils.Const;
import com.modules.sys.oauth2.TokenGenerator;

/**
* @Description: TODO
* @author LGC
* @date 2018年9月19日
* @version V1.0
*/
@Service("tokenServiceTmp")
@Transactional
public class TokenServiceImpl implements TokenService {

	@Autowired
	private EntityManager em;
	
	@Autowired
	private TokenRepository tokenRepository;
	
	@Autowired
	private DeviceCodeRepository dr;
	
	@Override
	public String saveOrUpdateToken(Long userId) {
		// 生成一个token
		String token = TokenGenerator.generateValue();
		
		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = new Date(now.getTime() + Const.EXPIRE_TIEM);
		
		// 判断是否生成过token
		TokenEntity tokenEntity = tokenRepository.findByUserId(userId);
		if(tokenEntity == null) {
			tokenEntity = new TokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setCreateTime(now);
			tokenEntity.setExpireTime(expireTime);
			em.persist(tokenEntity);
		} else {
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			em.merge(tokenEntity);
		}
		
		return token;
	}

	@Override
	public TokenEntity getTokenByUserId(Long userId) {
		return tokenRepository.findByUserId(userId);
	}
	
	@Override
	public TokenEntity getToken(String token) {
		return tokenRepository.findByToken(token);
	}

	@Override
	public MUserEntity getUserById(Long id) {
		return em.find(MUserEntity.class, id);
	}

	@Override
	public List<DeviceCodeEntity> findByUserId(Long id) {
		return dr.findByUserId(id);
	}

}
